﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace AVCUMPlatform.HelperLibrary
{
    public class HTTPHelper
    {
        /// <summary>
        /// 默认超时
        /// </summary>
        const int defaultTimeout = 30 * 1000;

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
        /// <summary>
        /// GET
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="token"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static T Get<T>(string url, string token = null, int timeout = defaultTimeout)
        {
            string res = HttpGet(url, token, timeout);
            return JsonConvert.DeserializeObject<T>(res);
        }

        /// <summary>
        /// GET
        /// </summary>
        /// <param name="url"></param>
        /// <param name="token"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static string HttpGet(string url, string token = null, int timeout = defaultTimeout)
        {
            try
            {
                HttpClient client = new HttpClient();
                if (url.StartsWith("https", System.StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 |
                                                           SecurityProtocolType
                                                               .Tls12; //必须加上这一句，根据需要更改值
                    var handler = new HttpClientHandler();
                    handler.ServerCertificateCustomValidationCallback = CheckValidationResult;
                    client = new HttpClient(handler);
                    client.DefaultRequestVersion = HttpVersion.Version11;
                }
                client.Timeout = TimeSpan.FromMilliseconds(timeout);
                var msg = new HttpRequestMessage(HttpMethod.Get, url);
                if (!string.IsNullOrEmpty(token))
                {
                    msg.Headers.Add("token", token);
                }
                HttpResponseMessage response = client.Send(msg);
                //response.EnsureSuccessStatusCode();
                StreamReader myreader = new StreamReader(response.Content.ReadAsStream(), Encoding.UTF8);
                string responseText = myreader.ReadToEnd();
                myreader.Close();
                return responseText;
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
                return "";
            }
        }

        /// <summary>
        /// Post
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="token"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static T Post<T>(string url, dynamic param, string token = null, int timeout = defaultTimeout)
        {
            try
            {
                string paramStr = JsonConvert.SerializeObject(param);
                string res = HttpPost(url, paramStr, token, timeout);
                return JsonConvert.DeserializeObject<T>(res);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <param name="token"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static string HttpPost(string url, string json, string token = null, int timeout = defaultTimeout)
        {
            try
            {
                HttpClient client = new HttpClient();
                if (url.StartsWith("https", System.StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 |
                                                           SecurityProtocolType
                                                               .Tls12; //必须加上这一句，根据需要更改值
                    var handler = new HttpClientHandler();
                    handler.ServerCertificateCustomValidationCallback = CheckValidationResult;
                    client = new HttpClient(handler);
                    client.DefaultRequestVersion = HttpVersion.Version11;
                }
                client.Timeout = TimeSpan.FromMilliseconds(timeout);
                var msg = new HttpRequestMessage(HttpMethod.Post, url);
                if (!string.IsNullOrEmpty(token))
                {
                    msg.Headers.Add("token", token);
                }
                msg.Content = new StringContent(json, Encoding.UTF8, "application/json");
                HttpResponseMessage response = client.Send(msg);
                //response.EnsureSuccessStatusCode();
                StreamReader myreader = new StreamReader(response.Content.ReadAsStream(), Encoding.UTF8);
                string responseText = myreader.ReadToEnd();
                myreader.Close();
                return responseText;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
